<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.png">
  <link rel="mask-icon" href="/images/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"./public/search.xml"};
  </script>

  <meta name="description" content="深入理解JS中的面向对象程序设计思想，包括各种设计模式">
<meta property="og:type" content="article">
<meta property="og:title" content="面向对象的程序设计(基于ES5)">
<meta property="og:url" content="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/index.html">
<meta property="og:site_name" content="共你云雨">
<meta property="og:description" content="深入理解JS中的面向对象程序设计思想，包括各种设计模式">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-09T08:46:41.056Z">
<meta property="article:modified_time" content="2020-03-09T08:46:42.450Z">
<meta property="article:author" content="Edison">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>面向对象的程序设计(基于ES5) | 共你云雨</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	<a href="https://github.com/mamba666" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">共你云雨</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Edison">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="共你云雨">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          面向对象的程序设计(基于ES5)
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-03-09 16:46:41 / 修改时间：16:46:42" itemprop="dateCreated datePublished" datetime="2020-03-09T16:46:41+08:00">2020-03-09</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <hr>
<h2 id="深入理解JS中的面向对象程序设计思想，包括各种设计模式"><a href="#深入理解JS中的面向对象程序设计思想，包括各种设计模式" class="headerlink" title="深入理解JS中的面向对象程序设计思想，包括各种设计模式"></a>深入理解JS中的面向对象程序设计思想，包括各种设计模式</h2><a id="more"></a>

<h2 id="理解对象"><a href="#理解对象" class="headerlink" title="理解对象"></a>理解对象</h2><p>创建一个最简单的对象方法就是直接创建一个Object的实例，然后在去添加属性和方法,最早期JS创建对象的方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p=<span class="keyword">new</span> <span class="built_in">Object</span>()</span><br><span class="line">p.name=<span class="string">"edison"</span></span><br><span class="line">p.age=<span class="number">22</span></span><br><span class="line">p.sayName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;...&#125;</span><br></pre></td></tr></table></figure>

<p>后来对象字面量称为主流，改写以上代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p=&#123;</span><br><span class="line">    name:<span class="string">"edison"</span></span><br><span class="line">    age:<span class="number">22</span></span><br><span class="line">    sayName:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;...&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="属性类型"><a href="#属性类型" class="headerlink" title="属性类型"></a>属性类型</h3><pre><code>ES在定义只有内部才用的特性时，描述了属性的各种特征。定义这些特性是为了实现JS引擎用的，所以在JS中不能直接访问他们，将特性用两对中括号括起来。

共有两种属性类型：数据属性和访问器属性</code></pre><h4 id="数据属性"><a href="#数据属性" class="headerlink" title="数据属性"></a>数据属性</h4><p>数据属性包含一个数据值的位置，这个位置可以写入和读取，共有4个特性描述</p>
<ul>
<li>[[Configurable]] : 表示能否通过delete删除属性从而重新定义属性，能否修改属性的特性，或者能否把属性修改为访问器属性</li>
<li>[[Enumerable]]:表示能否通过for-in循环返回属性。</li>
<li>[[Writable]]：表示能否修改属性的值。</li>
<li>[[Value]]：包含这个属性的数据值。读取属性值的时候，从这个位置读；写入属性值的时候，把新值保存在这个位置。这个特性的默认值为undefined。</li>
</ul>
<p>对于像前面例子中那样直接在对象上定义的属性，它们的[[Configurable]]、[[Enumerable]]和[[Writable]]特性都被设置为true，而[[Value]]特性被设置为指定的值。</p>
<p>要修改默认属性的值，需要使用Object.defineProperty()，接收三个参数：属性的所在的对象，属性的名字和一个描述符(descriptor)对象。其中descriptor的值必须是数据属性的4个特性中的一个或多个。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p=&#123;&#125;</span><br><span class="line"><span class="built_in">Object</span>.defineProperty(p,<span class="string">"name"</span>,&#123;</span><br><span class="line">	writable:<span class="literal">false</span>,</span><br><span class="line">	value:<span class="string">"edison"</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(p.name)   <span class="comment">//==&gt;edison</span></span><br><span class="line">p.name=<span class="string">"kobe"</span></span><br><span class="line"><span class="built_in">console</span>.log(p.name)   <span class="comment">//==&gt;edison    因为设置了writable为false，即无法修改属性的值</span></span><br></pre></td></tr></table></figure>

<p>也就是说，可以多次调用Object.defineProperty()方法修改同一个属性，但在把configurable特性设置为false之后就会有限制了。 在调用Object.defineProperty()方法时，如果不指定，configurable、enumerable和writable特性的默认值都是false。多数情况下，可能都没有必要利用Object.defineProperty()方法提供的这些高级功能。不过，理解这些概念对理解JavaScript对象却非常有用。</p>
<h4 id="访问器属性"><a href="#访问器属性" class="headerlink" title="访问器属性"></a>访问器属性</h4><p>访问器属性不包含数据值，而是包含一对getter和setter函数(两者都是非必须的)</p>
<p>在读取访问器属性时会调用getter，其负责返回有效值；在写入访问器属性时会调用setter函数并且传入新值，决定如何处理数据</p>
<ul>
<li>[[Configurable]] : 表示能否通过delete删除属性从而重新定义属性，能否修改属性的特性，或者能否把属性修改为访问器属性</li>
<li>[[Enumerable]]:表示能否通过for-in循环返回属性。<br>[[Get]]：在读取属性时调用的函数。默认值为undefined。<br>[[Set]]：在写入属性时调用的函数。默认值为undefined。</li>
</ul>
<p>访问器属性不能直接定义，必须使用Object.defineProperty</p>
<h3 id="定义多个属性"><a href="#定义多个属性" class="headerlink" title="定义多个属性"></a>定义多个属性</h3><pre><code>由于为对象定义多个属性的可能性很大，ECMAScript 5又定义了一个Object.defineProperties\(\)方法。通过这个方法可以利用描述符一次性定义多个属性。</code></pre><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> book=&#123;&#125;</span><br><span class="line"><span class="built_in">Object</span>.defineProperties(book,&#123;</span><br><span class="line">    _year:&#123;</span><br><span class="line">        value:<span class="number">2004</span></span><br><span class="line">    &#125;,</span><br><span class="line">    edition:&#123;</span><br><span class="line">        value:<span class="number">1</span></span><br><span class="line">    &#125;,</span><br><span class="line">    year:&#123;</span><br><span class="line">        <span class="keyword">get</span>:function()&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>._year</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="keyword">set</span>:function(newValue)&#123;</span><br><span class="line">            <span class="keyword">if</span>(newValue&gt;<span class="number">2004</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="读取属性的特性"><a href="#读取属性的特性" class="headerlink" title="读取属性的特性"></a>读取属性的特性</h3><h2 id="创建对象"><a href="#创建对象" class="headerlink" title="创建对象"></a>创建对象</h2><h3 id="工厂模式"><a href="#工厂模式" class="headerlink" title="工厂模式"></a>工厂模式</h3><pre><code>抽象了创建对象的具体过程。因为js无法创建类，故发明了一种函数，用函数来封装以特定接口创建对象的细节</code></pre><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createPerson</span>(<span class="params">name,age,job</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> o=<span class="keyword">new</span> <span class="built_in">Object</span>()</span><br><span class="line">	o.name=name</span><br><span class="line">	o.age=age</span><br><span class="line">	o.job=job</span><br><span class="line">	o.sayName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		alert(<span class="keyword">this</span>.name)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> o</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> p1=createPerson(<span class="string">"kobe"</span>,<span class="number">40</span>,<span class="string">"player"</span>)</span><br><span class="line"><span class="built_in">console</span>.log(p1.name)    <span class="comment">//==&gt;kobe</span></span><br></pre></td></tr></table></figure>

<p>虽然工厂模式解决了创建多个相似对象的问题，但是没有解决对象的识别问题（即怎样知道一个对象的类型）</p>
<h3 id="构造函数模式"><a href="#构造函数模式" class="headerlink" title="构造函数模式"></a>构造函数模式</h3><pre><code>ES中的构造函数可以用来创建特定类型的对象（构造函数名开头要使用大写）。</code></pre><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name,age,job</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.name=name</span><br><span class="line">	<span class="keyword">this</span>.age=age</span><br><span class="line">	<span class="keyword">this</span>.job=job</span><br><span class="line">	<span class="keyword">this</span>.sayName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		alert(<span class="keyword">this</span>.name)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> p1=<span class="keyword">new</span> Person(<span class="string">"kobe"</span>,<span class="number">40</span>,<span class="string">"player"</span>)</span><br><span class="line"><span class="built_in">console</span>.log(p1.name)</span><br></pre></td></tr></table></figure>

<p>在创建Person的新实例时，必须使用new操作符，会经过4个步骤：</p>
<ol>
<li>创建一个新对象</li>
<li>将构造函数的作用域赋给新对象</li>
<li>执行构造函数中的代码</li>
<li>返回新对象</li>
</ol>
<p>在p1中，有一个constructor属性指向Person，对象的constructor属性最初使用来标识对象类型的，但是提到检测对象类型，还是instanceof操作符更可靠！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(p1.constructor===Person) <span class="comment">//==&gt;true</span></span><br><span class="line"><span class="built_in">console</span>.log(p1.constructor===<span class="built_in">Object</span>) <span class="comment">//==&gt;false</span></span><br><span class="line"><span class="built_in">console</span>.log(p1 <span class="keyword">instanceof</span> Person) <span class="comment">//==&gt;true</span></span><br><span class="line"><span class="built_in">console</span>.log(p1 <span class="keyword">instanceof</span> <span class="built_in">Object</span>) <span class="comment">//==&gt;true</span></span><br></pre></td></tr></table></figure>

<pre><code>创建自定义的构造函数意味着将来可以将它的实例标识为一种特定的类型，这也是构造函数模式胜过工厂模式的地方</code></pre><h4 id="将构造函数当作函数"><a href="#将构造函数当作函数" class="headerlink" title="将构造函数当作函数"></a>将构造函数当作函数</h4><pre><code>构造函数与其他函数唯一区别就是调用方式。但是构造函数也是函数，不存在定义构造函数的特殊语法。任何函数重要通过new来调用，那么它就可以当作构造函数。反之任何函数不通过new调用，那么它跟普通函数也不会有什么两样</code></pre><h4 id="构造函数的问题"><a href="#构造函数的问题" class="headerlink" title="构造函数的问题"></a>构造函数的问题</h4><pre><code>主要问题在于每个方法在每个实例上都要重新创建。</code></pre><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//两种声明是等价的</span></span><br><span class="line"><span class="keyword">this</span>.sayName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line"><span class="keyword">this</span>.sayName=<span class="keyword">new</span> <span class="built_in">Function</span>()</span><br></pre></td></tr></table></figure>

<p>这样没有必要，故可以将方法放到构造函数外部来解决。但是假如有很多方法，就需要在外部定义很多方法，这样一来就完全没有封装性可言！</p>
<h3 id="原型模式"><a href="#原型模式" class="headerlink" title="原型模式"></a>原型模式</h3><pre><code>每个函数都有一个原型prototype属性，这个属性是一个指针，指向由构造函数创建的实例的原型对象。</code></pre><p>这里直接将方法添加到Person的prototype属性中，构造函数成了空的，实际上所有的实例都是共享的，即创建出来的实例的属性方法都是一样的</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line">Person.prototype.name=<span class="string">"kobe"</span></span><br><span class="line">Person.prototype.age=<span class="number">40</span></span><br><span class="line">Person.prototype.job=<span class="string">"player"</span></span><br><span class="line">Person.prototype.sayName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="keyword">this</span>.name)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> p1=<span class="keyword">new</span> Person()</span><br><span class="line">p1.sayName()</span><br></pre></td></tr></table></figure>

<h4 id="理解原型对象"><a href="#理解原型对象" class="headerlink" title="理解原型对象"></a>理解原型对象</h4><pre><code>无论什么时候，只要创建了一个新的函数，就会生成一个prototype属性，其指向函数的原型对象。默认情况下，所有原型对象都会获得一个constructor属性，其指向prototype所在。</code></pre><p>p1中会有一个[prototype],虽然无法访问，但是可以通过isPrototypeOf方法判断是否与原型对象存在关系</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(Person.prototype.isPrototypeOf(p1))  ==&gt;<span class="comment">//TRUE   因为p1内部有一个指针指向Person.prototype</span></span><br></pre></td></tr></table></figure>

<p>在ES5中，有一个Object.getPrototypeOf方法，返回[[prototype]]的值，又因为其指向Person.prototype,实际返回对象原型（非常重要）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.getPrototypeOf(p1).name)   ==&gt;  <span class="comment">//"kobe"</span></span><br></pre></td></tr></table></figure>

<p>每当代码需要读取某个属性时，都会执行一次搜索，即找到需要搜索的属性名。搜索先从实例开始，如果找到了则返回该属性值；反之则继续搜索指针指向的原型对象，如果找到了则返回其属性值。</p>
<p>前面说过，原型最初只包含constructor属性，而改属性也是共享的，因此可以通过对象实例来访问。虽然可以通过实例访问保存在原型对象中的值，但是不能通过实例去修改。</p>
<p>假如在实例中添加了一个属性，恰好原型中也存在相同属性，则会在实例中创建它，自动屏蔽原型中的那个属性。实际上原理和上面说的一样，即搜索机制，先外后里。即使将设置过的实例属性设置为null，也不会将其回收！不过可以使用delete操作符去删除！</p>
<p>hasOwnProperty方法可以检测一个属性是存在与实例中，还是存在于原型中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(p1.hasOwnProperty(<span class="string">"name"</span>))</span><br></pre></td></tr></table></figure>

<h4 id="原型与in操作符"><a href="#原型与in操作符" class="headerlink" title="原型与in操作符"></a>原型与in操作符</h4><pre><code>有两种方式去使用in操作符：单独使用和在for-in循环中。</code></pre><p>单独使用时，in操作符会在通过对象能够访问给定属性时返回true，与属性存在于原型还是实例无关。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">"name"</span> <span class="keyword">in</span> Person)   <span class="comment">//==&gt;true</span></span><br></pre></td></tr></table></figure>

<h4 id="更简洁的原型语法"><a href="#更简洁的原型语法" class="headerlink" title="更简洁的原型语法"></a>更简洁的原型语法</h4><p>重写之前的代码。之前说过，没创建一个函数，就会同时创建它的原型对象，这个对象也会获得constructor属性指向函数。但是这里的写法完全重写了默认的原型对象，故使得constructor不再指向Person。</p>
<p>如果constructor的值真的很重要，则可以加上如下代码（用注释写出）.但是这样会使得它的[[Enumerable]]特性被设置为true。但是原生的constructor属性是不可以枚举的，因此可以试试Object.defineProperty方法，同样用注释写出。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line">Person.prototype=&#123;</span><br><span class="line">    <span class="comment">//constructor:Person,</span></span><br><span class="line">	name:<span class="string">"kobe"</span>,</span><br><span class="line">	age:<span class="number">40</span>,</span><br><span class="line">	job:<span class="string">"player"</span>,</span><br><span class="line">	sayName:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		<span class="built_in">console</span>.log(<span class="keyword">this</span>.name)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Object.defineProperty(Person.prototype,"constructor",&#123;</span></span><br><span class="line"><span class="comment">//     enumerable:false,</span></span><br><span class="line"><span class="comment">//     value:Person</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br></pre></td></tr></table></figure>

<h4 id="原型的动态性"><a href="#原型的动态性" class="headerlink" title="原型的动态性"></a>原型的动态性</h4><pre><code>因为原型对象和构造函数和实例都是通过指针来连接的，这种连接是松散的。如果重写了原型对象，则实例的指针还是指向原来的原型对象，但是构造函数指向了新的原型对象，可是构造函数和实例之间没有并没有关联。虽然新旧两个原型对象constructor都指向构造函数Person，但是实例还是指向的原来的。</code></pre><h4 id="原生对象的原型"><a href="#原生对象的原型" class="headerlink" title="原生对象的原型"></a>原生对象的原型</h4><pre><code>原型模式的重要性不仅体现在创建自定义类型方面，就连所有原生的引用类型，都是采用这种模式创建的。所有原生引用类型（Object、Array、String，等等）都在其构造函数的原型上定义了方法。 </code></pre><h4 id="原型对象的问题"><a href="#原型对象的问题" class="headerlink" title="原型对象的问题"></a>原型对象的问题</h4><pre><code>原型模式省略了构造函数的传参，使得每个实例都都具有相同的属性，但是这不是最大的缺点。最大的问题在于其共享本质导致的。</code></pre><p>这种共享对于函数来说非常合适！但是对于包含引用类型的属性来说，问题突出。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line">Person.prototype=&#123;</span><br><span class="line">	<span class="keyword">constructor</span>:Person,</span><br><span class="line">	name:"kobe",</span><br><span class="line">	age:40,</span><br><span class="line">	job:"player",</span><br><span class="line">	sayName:function()&#123;</span><br><span class="line">		<span class="built_in">console</span>.log(<span class="keyword">this</span>.name)</span><br><span class="line">	&#125;,</span><br><span class="line">	friends:[<span class="string">"jordan"</span>,<span class="string">"macRady"</span>]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> p1=<span class="keyword">new</span> Person()</span><br><span class="line"><span class="keyword">var</span> p2=<span class="keyword">new</span> Person()</span><br><span class="line">p1.friends.push(<span class="string">"james"</span>)</span><br><span class="line"><span class="built_in">console</span>.log(p1.friends)  <span class="comment">//==&gt;[ 'jordan', 'macRady', 'james' ]</span></span><br><span class="line"><span class="built_in">console</span>.log(p2.friends)  <span class="comment">//==&gt;[ 'jordan', 'macRady', 'james' ]</span></span><br></pre></td></tr></table></figure>

<p>可以看到只对p1进行了push操作，但是同时也影响了p2！因为friends存在于Person.prototype中，修改了p1.friends.push也意味着p2的也被修改了，所以又出来一种新的设计模式！</p>
<h3 id="组合使用构造函数和原型模式"><a href="#组合使用构造函数和原型模式" class="headerlink" title="组合使用构造函数和原型模式"></a>组合使用构造函数和原型模式</h3><pre><code>构造函数用于定义实例属性，而原型模式用于定义方法和共享的属性。</code></pre><p>重写之前的代码,分工合作.这也是用来定义引用类型的默认模式。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">age,name,job</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.age=age</span><br><span class="line">	<span class="keyword">this</span>.name=name</span><br><span class="line">	<span class="keyword">this</span>.job=job</span><br><span class="line">	<span class="keyword">this</span>.friends=[<span class="string">"jordan"</span>,<span class="string">"macRady"</span>]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Person.prototype=&#123;</span><br><span class="line">	<span class="keyword">constructor</span>:Person</span><br><span class="line">	sayName:function()&#123;</span><br><span class="line">		alert(<span class="keyword">this</span>.name)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="动态原型模式"><a href="#动态原型模式" class="headerlink" title="动态原型模式"></a>动态原型模式</h3><pre><code>构造加原型显得封装度不够，故动态原型模式把所有的信息都封装在了构造函数中</code></pre><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">age,name,job</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.age=age</span><br><span class="line">	<span class="keyword">this</span>.name=name</span><br><span class="line">	<span class="keyword">this</span>.job=job</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">typeof</span> <span class="keyword">this</span>.sayName!=<span class="string">"function"</span>)&#123;</span><br><span class="line">        Person.prototype.sayName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="keyword">this</span>.name)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="寄生构造函数模式"><a href="#寄生构造函数模式" class="headerlink" title="寄生构造函数模式"></a>寄生构造函数模式</h3><pre><code>通常，在前述的几种模式都不适用的情况下，可以使用寄生（parasitic）构造函数模式。这种模式的基本思想是创建一个函数，该函数的作用仅仅是封装创建对象的代码，然后再返回新创建的对象；但从表面上看，这个函数又很像是典型的构造函数。但是不建议使用</code></pre><h3 id="稳妥构造函数模式"><a href="#稳妥构造函数模式" class="headerlink" title="稳妥构造函数模式"></a>稳妥构造函数模式</h3><pre><code>道格拉斯•克罗克福德（Douglas Crockford）发明了JavaScript中的稳妥对象（durable objects）这个概念。所谓稳妥对象，指的是没有公共属性，而且其方法也不引用this的对象。稳妥对象最适合在一些安全的环境中（这些环境中会禁止使用this和new），或者在防止数据被其他应用程序（如Mashup程序）改动时使用。稳妥构造函数遵循与寄生构造函数类似的模式，但有两点不同：一是新创建对象的实例方法不引用this；二是不使用new操作符调用构造函数。按照稳妥构造函数的要求，可以将前面的Person构造函数重写如下。</code></pre><h2 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h2><pre><code>ES只支持实现继承，其依靠原型链来实现</code></pre><h3 id="原型链"><a href="#原型链" class="headerlink" title="原型链"></a>原型链</h3><pre><code>基本思想是利用原型让一个引用类型继承另外一个引用类型的属性和方法。</code></pre><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Super</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">Super.prototype.say=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">"this is Super"</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Sub</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">Sub.prototype=<span class="keyword">new</span> Super()</span><br><span class="line"></span><br><span class="line">Sub.prototype.say()   <span class="comment">//==&gt;Sub继承了Super的方法</span></span><br></pre></td></tr></table></figure>



    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"># js</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B/" rel="prev" title="面向对象编程--类的创建，数据的封装">
      <i class="fa fa-chevron-left"></i> 面向对象编程--类的创建，数据的封装
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/03/09/%E6%95%B0%E6%8D%AE%E2%80%94%E5%8F%98%E9%87%8F%E2%80%94%E5%86%85%E5%AD%98%E6%A6%82%E5%BF%B5%E8%BE%A8%E6%9E%90/" rel="next" title="数据—变量—内存概念辨析">
      数据—变量—内存概念辨析 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#深入理解JS中的面向对象程序设计思想，包括各种设计模式"><span class="nav-number">1.</span> <span class="nav-text">深入理解JS中的面向对象程序设计思想，包括各种设计模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#理解对象"><span class="nav-number">2.</span> <span class="nav-text">理解对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#属性类型"><span class="nav-number">2.1.</span> <span class="nav-text">属性类型</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#数据属性"><span class="nav-number">2.1.1.</span> <span class="nav-text">数据属性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#访问器属性"><span class="nav-number">2.1.2.</span> <span class="nav-text">访问器属性</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定义多个属性"><span class="nav-number">2.2.</span> <span class="nav-text">定义多个属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#读取属性的特性"><span class="nav-number">2.3.</span> <span class="nav-text">读取属性的特性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建对象"><span class="nav-number">3.</span> <span class="nav-text">创建对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#工厂模式"><span class="nav-number">3.1.</span> <span class="nav-text">工厂模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#构造函数模式"><span class="nav-number">3.2.</span> <span class="nav-text">构造函数模式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#将构造函数当作函数"><span class="nav-number">3.2.1.</span> <span class="nav-text">将构造函数当作函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#构造函数的问题"><span class="nav-number">3.2.2.</span> <span class="nav-text">构造函数的问题</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#原型模式"><span class="nav-number">3.3.</span> <span class="nav-text">原型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#理解原型对象"><span class="nav-number">3.3.1.</span> <span class="nav-text">理解原型对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原型与in操作符"><span class="nav-number">3.3.2.</span> <span class="nav-text">原型与in操作符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#更简洁的原型语法"><span class="nav-number">3.3.3.</span> <span class="nav-text">更简洁的原型语法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原型的动态性"><span class="nav-number">3.3.4.</span> <span class="nav-text">原型的动态性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原生对象的原型"><span class="nav-number">3.3.5.</span> <span class="nav-text">原生对象的原型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原型对象的问题"><span class="nav-number">3.3.6.</span> <span class="nav-text">原型对象的问题</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#组合使用构造函数和原型模式"><span class="nav-number">3.4.</span> <span class="nav-text">组合使用构造函数和原型模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#动态原型模式"><span class="nav-number">3.5.</span> <span class="nav-text">动态原型模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#寄生构造函数模式"><span class="nav-number">3.6.</span> <span class="nav-text">寄生构造函数模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#稳妥构造函数模式"><span class="nav-number">3.7.</span> <span class="nav-text">稳妥构造函数模式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#继承"><span class="nav-number">4.</span> <span class="nav-text">继承</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#原型链"><span class="nav-number">4.1.</span> <span class="nav-text">原型链</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Edison</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">124</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
</div>
  <div class="powered-by">山高水远  一定相见
  </div>
<div></div>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">至今已写107.1k字</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
